<?php
namespace app\mp\admin;
use app\system\admin\Admin;
use app\common\service\StallFeed as StallFeedService;
use app\common\service\StallCost as StallCostService;
use app\common\service\StallBill as StallBillService;
use app\common\service\StallBillFeed as StallBillFeedService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\Order as OrderService;
class StallBillFeed extends Admin
{
	/**
     * 费用单记录
     *
     * @author 飞燕
     * @date 2020年3月18日
     *
     */
    public function stallBillFeedDetail()
    {
    	$stallBillId  = $this->request->param('stall_bill_id/d', 0);
        $stallId  = $this->request->param('stall_id/d', 0);
		//if(!$stallBillId) return $this->error('缺少stall_bill_id参数');
		$stallBillService=new StallBillService();
		$sbInfo=$stallBillService->getInfoById($stallBillId);
		$stallsKV= getStallsKV();

    	if ($this->request->isAjax() ||$this->request->param('export/d',0)) {
            $export     = $this->request->param('export/d', 0);
			$stallCostService=new StallCostService();
			$stallFeedService=new StallFeedService();
			$orderService=new OrderService();
            $stallBillFeedService=new StallBillFeedService();
			$orderMaterialService=new OrderMaterialService();
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $billmonthDate    = $this->request->param('create_date_range/s');
            $paytype    = $this->request->param('pay_type/d', '');
            $max_moeny    = $this->request->param('max_money/d', '');
            $min_money    = $this->request->param('min_money/d', '');
            $where      = $data = [];
            if ($min_money) {
                $where[] = ['settle_amount', '>=', $min_money];
            }
            if ($max_moeny) {
                $where[] = ['settle_amount', '<=', $max_moeny];
            }
            if ($paytype) {
                $where[] = ['pay_type', '=', $paytype];
            }
            if ($stallId) {
                $where[] = ['stall_id', '=', $stallId];
            }
            if ($billmonthDate != '') {
                list($startTime, $endTime) =explode('~', $billmonthDate);// array_map('strtotime', explode('~', $billmonthDate));
                $where[] = ['pay_month', 'between', [substr($startTime,0,7), substr(trim($endTime),0,7)]];
            }
            if ($export) {
    			set_time_limit(0);
    			ini_set('memory_limit', '1024M');
    			$page = 1;
    			$limit = 99999;
    		}
    		if($stallBillId){
                $where = [
                    ['stall_bill_id', '=', $stallBillId],
                ];
            }
            $systemUserKV = getSystemUserKV(null);
            $list=db('stall_bill_feed sf')->where($where)
                ->join('stall_feed st', "sf.stall_feed_id=st.id", 'left')
                ->field("*")->page($page)->limit($limit)->order('sf.id desc')->select();
			foreach ($list as $key => $value) {
				$sfInfo=$stallFeedService->getInfoById($value['stall_feed_id']);
                if(empty($sfInfo['mInfo'])){
                    $sfInfo['mInfo']=["color"=>'',"colornum"=>'','material_sku'=>'','model'=>'','name'=>$value['material_name'],'type'=>'','unit'=>"",'customer_price'=>''];
                }
				$list[$key]['stall_name']= arrayGet($stallsKV, $sfInfo['stall_id'], '');
				$list[$key]['amount']=round(floatval($sfInfo['billing_caigou_count_feed'])*floatval($sfInfo['caigou_unitprice']),2);
				$list[$key]['sfInfo']=$sfInfo;
                $list[$key]['caigou_unitprice']=$sfInfo['caigou_unitprice'] ?? 0;
                $list[$key]['customer_price']=$sfInfo['mInfo']['customer_price'] ?? 0;
                $list[$key]['settle_unitprice']=$sfInfo['settle_unitprice'];
                $list[$key]['settle_amount']=$sfInfo['settle_amount'];$sfInfo['mInfo']['name']=empty($sfInfo['mInfo']['name'])?'':$sfInfo['mInfo']['name'];
                $list[$key]['mInfo']=$sfInfo['mInfo'];
				$omInfo=$orderMaterialService->getInfoById($sfInfo['order_material_id'], 'tiaoshu,is_share');
                $list[$key]['win_money']=isset($omInfo['win_money'])? $omInfo['win_money'] :0;
				$list[$key]['tiaoshu']=$omInfo?$omInfo['tiaoshu']:0;
                $list[$key]['admin_name']= arrayGet($systemUserKV,$value['admin_id'], '');
                $list[$key]['caigou_name']= arrayGet($systemUserKV,$value['caigou_user_id'], '');
                $list[$key]['check_name']= arrayGet($systemUserKV,$value['check_uid'], '');
				$list[$key]['oInfo']=$orderService->getInfoById($sfInfo['order_id'], "create_time as order_time,caigou_over_time,sku,factory_id,client_status");
				$list[$key]['total_amount']=round(floatval($list[$key]['amount'])- array_sum(array_column($sfInfo['scInfo'], 'stall_cost_money')),2);
			}
			if ($export) {
    			$this->_exportXls('账单-' .date('YmdHis'), $list);
    			exit;
    		}
    		$data['status']=4;
            $data['statData']=[];
    		$data['count'] = db('stall_bill_feed sf')->join('stall_feed st', "sf.stall_feed_id=st.id", 'left')->where($where)->count('*');
    		$data['data'] = $list;
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}
		$sbInfo['stall_name']= arrayGet($stallsKV, $sbInfo['stall_id'], '');
		$sbInfo['bill_time']= date("Y-m-d h:i:s",$sbInfo['create_time']);
    	$assign = [
    		'stallBillId' => $stallBillId,
			'sbInfo'=>$sbInfo
    	];
    	return $this->assign($assign)->fetch();
    }
	/**
	 * 导出
	 *
	 * @author King
	 * @date 2020年8月19日
	 *
	 */
	private function _exportXls($fileName, &$data) {
    	$head = ['下单日期','订单号','物料sku','供应商','材料名称','颜色','供应商单日期','供应商单单号','采购数量','采购单价','MES单价','采购条数','单位','采购公斤价','采购公斤数',
            '结算单价','结算金额','采购总金额','总计','费用单类型','费用单金额（元）','结款方式','材料类型','归属月份','工厂分配','是否废除','盈亏情况'];
        $params = [];
        $exportdata = [];
        $factoryKV = [0=>'']+getFactoryKV(true);
        $pay_type=[''=>'',1=>'月结',2=>'现金'];
        $material_type=[''=>'','fabric'=>'面料','lining'=>'里料','accessories'=>'辅料'];
        foreach ($data as $k => $v) {
            $exportdata[] = [
                isset($v['oInfo']['order_time'])? date('Y-m-d H:i:s', $v['oInfo']['order_time']) :'',
                $v['sfInfo']['client_ordernum'],
                isset($v['oInfo']['sku']) ? $v['oInfo']['sku'] :'',
                $v['stall_name'],
                $v['sfInfo']['mInfo']['name'],
                $v['sfInfo']['mInfo']['color'],
                //$v['oInfo']['caigou_over_time']!=0?date('Y-m-d H:i:s', $v['oInfo']['caigou_over_time']):'',
                $v['sfInfo']['stall_order_time']==0 ? '':date('Y-m-d', $v['sfInfo']['stall_order_time']),
                $v['sfInfo']['stall_order'],
                $v['sfInfo']['billing_caigou_count_feed'],
                $v['sfInfo']['caigou_unitprice'],
                $v['customer_price'],
                $v['tiaoshu'],
                $v['sfInfo']['mInfo']['unit'],
                $v['sfInfo']['billing_caigou_kgprice'],
                $v['sfInfo']['billing_caigou_kgcount'],
                $v['settle_unitprice'],
                $v['settle_amount'],
                $v['amount'],
                $v['total_amount'],
                isset($v['stall_cost_type'])?$v['stall_cost_type']:'',
                isset($v['stall_cost_money'])?$v['stall_cost_money']:'',
                $pay_type[$v['pay_type']],
                $material_type[$v['sfInfo']['mInfo']['type']],
                $v['pay_month'],
                isset($v['oInfo']['factory_id'])? $factoryKV[$v['oInfo']['factory_id']] :'',
                isset($v['oInfo']['client_status']) ? ( $v['oInfo']['client_status']==99 ? '已废除': '未废除') : '未废除',
                isset($v['win_money'])? $v['win_money'] :0.00,

            ];
        }
        $params['file'] = $fileName;
        $params['sheet'] = [
            [
                'head' => $head, // 表头
                'data' => $exportdata,
            ],
        ];
        unset($data);
        plugins_run('excel/excel/export', $params);
    }
	private function _exportXls1($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
			$data[] = [
				//$picData,
				date('Y-m-d H:i:s', $v['oInfo']['order_time']),
				$v['sfInfo']['client_ordernum'],
				$v['stall_name'],
				$v['sfInfo']['mInfo']['name'],
				$v['sfInfo']['mInfo']['color'],
				date('Y-m-d H:i:s', $v['oInfo']['caigou_over_time']),
				$v['sfInfo']['stall_order'],
				$v['sfInfo']['billing_caigou_count_feed'],
				$v['sfInfo']['caigou_unitprice'],
				$v['amount'],
				$v['factory_name'],
				$v['caigou_over_time'] ? date('Y-m-d H:i:s', $v['caigou_over_time']) : '',
				$v['caichuang_over_time'] ? date('Y-m-d H:i:s', $v['caichuang_over_time']) : '',
				$v['chejian_over_time'] ? date('Y-m-d H:i:s', $v['chejian_over_time']) : '',
				$v['tail_over_time'] ? date('Y-m-d H:i:s', $v['tail_over_time']) : '',
				$v['group_name'],
				$v['remark'],
				$v['factory_outgo_name'],
				arrayGet($v['sInfo'], 'cost', 0),
				arrayGet(config('mimo.order_from'), $v['is_auto_import'], ''),
				arrayGet($v['sInfo'], 'sku_type', ''),
				arrayGet($v['sInfo'], 'is_public', 0) ? '是':'否',
				arrayGet($v['sInfo'], 'special_process_a_name', ''),
				arrayGet($v['sInfo'], 'special_process_a_count', 0),
				arrayGet($v['sInfo'], 'special_process_a_unitprice', 0),
				arrayGet($v['sInfo'], 'special_process_a_price', 0),
				arrayGet($v['sInfo'], 'price', 0),
				$v['shipment_time'] ? date('m月d日', $v['shipment_time']) : '',
			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['下单日期','订单号','供应商','材料名称','颜色','采购日期','供应商单单号','采购数量','采购单价','采购总金额','费用单类型/费用单金额（元）','总计'], // 表头
				'data' => $data,
			],
		];
		unset($list);
		plugins_run('excel/excel/export', $params);
	}
}

